<template>
  <div class="order-management">
    <!-- 查询区域 -->
    <el-card style="margin-bottom: 20px;">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-input v-model="search.userName" placeholder="用户昵称模糊搜索" prefix-icon="el-icon-search" />
        </el-col>
        <el-col :span="6">
          <el-select v-model="search.status" placeholder="按状态筛选" clearable>
            <el-option
              v-for="(status, index) in orderState"
              :key="index"
              :label="status"
              :value="index"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="search.orderType" placeholder="按订单类型筛选" clearable>
            <el-option
              v-for="(type, index) in orderTypes"
              :key="index"
              :label="type"
              :value="index"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="fetchData" icon="el-icon-search">搜索</el-button>
          <el-button @click="resetSearch" icon="el-icon-refresh">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 表格 -->
    <el-table :data="displayedOrders" border @cell-click="handleCellClick" style="width: 100% ">
      <el-table-column prop="userName" label="此订单用户昵称"></el-table-column>
      <el-table-column prop="phone" label="用户电话号码"></el-table-column>
      <el-table-column prop="orderType" label="订单类型">
        <template slot-scope="scope">
          {{ scope.row.orderType == 'NORMAL' ? '普通订单' : '高级订单' }}
        </template>
      </el-table-column>
      <el-table-column prop="currentStatus" label="订单状态">
        <template slot-scope="scope">
          {{ orderState[scope.row.currentStatus] }}
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-row :gutter="10" class="action-buttons">
            <el-col :span="12" class="button-column">
              <el-button size="mini" icon="el-icon-edit-outline" @click.stop="updateOrderStatus(scope.row)">更新状态</el-button>
              <el-button size="mini" icon="el-icon-switch-button" @click.stop="toggleOrderValid(scope.row)">
                {{ scope.row.isValid ? '禁用订单' : '激活订单' }}
              </el-button>
              <el-button size="mini" icon="el-icon-chat-dot-round" @click.stop="openCommentDialog(scope.row)">评论</el-button>
            </el-col>
            <el-col :span="12" class="button-column">
              <el-button size="mini" icon="el-icon-time" @click.stop="openStatusHistoryDialog(scope.row)">状态历史</el-button>
              <el-button size="mini" icon="el-icon-view" @click.stop="previewImages(scope.row)">预览图片</el-button>
              <el-button size="mini" type="primary" icon="el-icon-download" @click.stop="downloadImages(scope.row.id)">下载ZIP</el-button>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空数据提示 -->
    <el-empty v-if="displayedOrders.length == 0 && !loading" description="暂无数据" />

    <!-- 加载中提示 -->
    <!-- <el-spinner v-if="loading" style="display: block; margin: 20px auto;" /> -->

    <!-- 分页 -->
    <el-pagination
      layout="prev, pager, next"
      :total="total"
      :page-size="pageSize"
      :current-page.sync="currentPage"
      @current-change="fetchData"
    />

    <!-- 图片预览弹窗 -->
    <el-dialog title="图片预览" :visible.sync="imagePreviewVisible">
      <el-pagination
        small
        layout="prev, pager, next"
        :total="selectedOrder?.imageIdList?.length || 0"
        :page-size="5"
        :current-page.sync="imagePage"
        @current-change="updateImagePreview"
      ></el-pagination>
      <div style="display: flex; flex-wrap: wrap;">
        <img
          v-for="id in currentImages"
          :key="id"
          :src="getImageUrl(id)"
          style="width: 150px; height: 120px; margin: 5px;"
        />
      </div>
    </el-dialog>

    <!-- 订单评论弹窗 -->
    <CommentDialog
      :visible.sync="commentDialogVisible"
      :order="selectedOrder"
      @saved="fetchData"
      @deleted="fetchData"
    />

    <!-- 状态管理弹窗 -->
    <StatusHistoryDialog
      :visible.sync="statusHistoryDialogVisible"
      :history="selectedOrder?.orderStatusHistoryList || []"
      :order-state="orderState"
    />
  </div>
</template>

<script>
import axios from 'axios';
import CommentDialog from '../../components/admin/CommentDialog.vue';
import StatusHistoryDialog from '../../components/admin/StatusHistoryDialog.vue';
import { mapState } from 'vuex';
export default {
  name: 'OrderListView',
  components: { CommentDialog, StatusHistoryDialog },
  data() {
    return {
      orderState: [],
      orderList: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      search: {
        userName: '',
        status: null,
        orderType: null,
      },
      orderTypes: ['普通订单', '高级订单'], // 订单类型列表
      loading: false,
      imagePreviewVisible: false,
      commentDialogVisible: false,
      statusHistoryDialogVisible: false,
      selectedOrder: null,
      imagePage: 1,
      imagesPerPage: 5,
    };
  },
  computed: {
    ...mapState(['user']),
    displayedOrders() {
      let list = this.orderList || [];

      // 用户昵称模糊搜索
      if (this.search.userName) {
        const keyword = this.search.userName.toLowerCase();
        list = list.filter(order =>
          order.userName && order.userName.toLowerCase().includes(keyword)
        );
      }

      // 状态筛选
      if (this.search.status !== null && this.search.status !== '') {
        const status = parseInt(this.search.status);
        list = list.filter(order => order.currentStatus == status);
      }

      // 订单类型筛选
      if (this.search.orderType !== null && this.search.orderType !== '') {
        const orderType = this.search.orderType == 0 ? 'NORMAL' : 'PREMIUM';
        list = list.filter(order => order.orderType == orderType);
      }

      return list;
    },
    currentImages() {
      if (!this.selectedOrder) return [];
      const start = (this.imagePage - 1) * this.imagesPerPage;
      const end = start + this.imagesPerPage;
      return this.selectedOrder.imageIdList.slice(start, end);
    }
  },
  created() {
    this.fetchData();
    this.setupAutoRefresh();
  },
  methods: {
    getImageUrl(imageId) {
      return `/api/admin/minio/getImage/${imageId}`;
    },
    async getOrderList() {
      try {
        this.loading = true;
        const res = await axios.get('/api/admin/order/getOrderList');
        if (res.data.code == 1) {
          this.total = res.data.data.total;
          this.orderList = res.data.data.orderList || [];
          this.orderState = res.data.data.orderState || [];
        } else {
          this.$message.error(res.data.msg || '获取订单列表失败');
        }
      } catch (error) {
        console.error('请求出错，请检查网络连接或接口地址:', error);
      } finally {
        this.loading = false;
      }
    },
    downloadImages(orderId) {
      window.open(`/api/admin/minio/downloadImage/${orderId}`, '_blank');
    },
    previewImages(order) {
      this.selectedOrder = order;
      this.imagePreviewVisible = true;
    },
    openCommentDialog(order) {
      this.selectedOrder = order;
      this.commentDialogVisible = true;
    },
    openStatusHistoryDialog(order) {
      this.selectedOrder = order;
      this.statusHistoryDialogVisible = true;
    },
    async updateOrderStatus(order) {
      try {
        await this.$confirm('确定将该订单更新到下一状态？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });

        const newStatus = order.currentStatus + 1;
        if (newStatus >= this.orderState.length) {
          this.$message.warning('当前订单已经失效，请先激活订单');
          return;
        }

        const res = await axios.put(`/api/admin/order/updateOrder/${order.id}/${newStatus}`);
        if (res.data.code == 1) {
          this.$message.success('状态更新成功');
          this.fetchData();
        } else {
          this.$message.error(res.data.msg || '更新失败');
        }
      } catch (error) {
        if (error == 'cancel') {
          console.log('用户取消操作');
          return;
        }
        this.$message.error('发生未知错误，请查看控制台日志');
        console.error(error);
      }
    },
    async toggleOrderValid(order) {
      this.$confirm(`确定${order.isValid ? '禁用' : '激活'}该订单？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        const res = await axios.put(`/api/admin/order/updateOrderIsValid/${order.id}`);
        if (res.data.code == 1) {
          this.$message.success('状态切换成功');
          this.fetchData();
        } else {
          this.$message.error(res.data.msg || '切换失败');
        }
      });
    },
    fetchData() {
      this.getOrderList();
    },
    handleCellClick(row) {
      this.selectedOrder = row;
    },
    updateImagePreview() {
      // 更新图片预览逻辑
    },
    setupAutoRefresh() {
      setInterval(() => {
        if (this.user.active&&this.$route.name=="OrderList") {
          this.fetchData();
        }
      }, 4000);
    },
    resetSearch() {
      this.search.userName = '';
      this.search.status = null;
      this.fetchData();
    }
  },
};
</script>

<style scoped>
.order-management {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.el-table {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;

}

.el-card {
  margin-bottom: 20px;
}

.el-input,
.el-select {
  width: 100%;
}

.el-button--mini {
  font-size: 12px;
  padding: 6px 10px;
}
/* 每个按钮占据一定的宽度，以便在小屏幕上也能排列整齐 */
.el-button--mini {
  width: 100%;
  margin-bottom: 10px;
}

@media (min-width: 768px) {
  .el-button--mini {
    width: auto;
  }
}

/* 调整 el-row 和 el-col 的间距 */
.el-row {
  margin-bottom: -10px; /* 抵消 gutter 带来的额外间距 */
}

.el-col {
  padding-bottom: 10px;
}


/* 确保按钮在同一行 */
.action-buttons {
  display: flex;
  flex-wrap: nowrap; /* 不允许换行 */
}

.button-column {
  display: flex;
  flex-direction: column;
  justify-content: center; /* 垂直居中 */
  padding-bottom: 10px; /* 调整底部间距 */
}

.button-column .el-button--mini {
  margin-bottom: 10px; /* 按钮之间的间距 */
  width: 100%; /* 使按钮占满整个列宽 */
}

.button-column .el-button--mini:last-child {
  margin-bottom: 0; /* 最后一个按钮不需要底部间距 */
}

@media (min-width: 768px) {
  .button-column .el-button--mini {
    width: auto; /* 在大屏幕上让按钮宽度自动适应内容 */
  }
}
</style>